﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace SAPBoAddonUI
{
    /// <summary>
    /// 范型类，用于对象（数组）和序列化的XML字符串之间的相互转换
    /// </summary>
    /// <typeparam name="ObjectType">指定的对象类型</typeparam>
    public class ObjectToXML<ObjectType>
    {
        /// <summary>
        /// 从对象（数组）转换成XML序列字符串
        /// </summary>
        /// <param name="obj">要转换的对象（数组）</param>
        /// <returns>XML序列字符串</returns>
        public string FromObjectToXML(ObjectType obj)
        {
            if (obj == null)
                return null;

            XmlSerializer x = new XmlSerializer(obj.GetType());
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            x.Serialize(sw, obj);
            string s = sb.ToString();

            return s;
        }
        /// <summary>
        /// 从XML字符串反序列化成对象（数组）
        /// </summary>
        /// <param name="s">要反序列化的XML字符串</param>
        /// <returns>对象（数组）</returns>
        public ObjectType FromXMLToObject(string s)
        {
            if (s == "" || s == null)
                return default(ObjectType);

            StringReader sr = new StringReader(s);
            XmlSerializer x = new XmlSerializer(typeof(ObjectType));
            ObjectType lc = (ObjectType)(x.Deserialize(sr));
            return lc;
        }

    }
}
